package com.example.pagingdemo.paging.movie;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.DataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import androidx.paging.PositionalDataSource;

import com.example.pagingdemo.api.Api;
import com.example.pagingdemo.api.RetrofitClient;
import com.example.pagingdemo.model.Movie;
import com.example.pagingdemo.model.Movies;
import com.example.pagingdemo.paging.AbsViewModel;
import com.example.pagingdemo.paging.PageConfig;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class MovieViewModel extends AbsViewModel<Movie> {

    @Override
    protected DataSource createDataSource() {
        return new MovieDataSource();
    }

    public class MovieDataSource extends PositionalDataSource<Movie> {

        @Override
        public void loadInitial(@NonNull LoadInitialParams params, @NonNull final LoadInitialCallback<Movie> callback) {
            Log.d("aaaa", "开始加载数据: ");
            int startPosition = 0;
            RetrofitClient.get().buildApi(Api.BASE_URL)
                    .getMovies(startPosition, PageConfig.PER_PAGE_SIZE)
                    .enqueue(new Callback<Movies>() {
                        @Override
                        public void onResponse(Call<Movies> call, Response<Movies> response) {
                            Movies body = response.body();
                            Log.d("aaaa", "获得数据: "+response.body());
                            if (body != null) {
                                callback.onResult(body.movies, body.start, body.total);
                            }
                        }

                        @Override
                        public void onFailure(Call<Movies> call, Throwable t) {

                        }
                    });
        }

        @Override
        public void loadRange(@NonNull LoadRangeParams params, @NonNull final LoadRangeCallback<Movie> callback) {
            Log.d("aaaa", "下一页数据: start:" + params.startPosition);
            RetrofitClient.get().buildApi(Api.BASE_URL)
                    .getMovies(params.startPosition, PageConfig.PER_PAGE_SIZE)
                    .enqueue(new Callback<Movies>() {
                        @Override
                        public void onResponse(Call<Movies> call, Response<Movies> response) {
                            Movies body = response.body();
                            Log.d("aaaa", "下一页获得数据: "+body);
                            if (body != null) {
                                callback.onResult(body.movies);
                            }
                        }

                        @Override
                        public void onFailure(Call<Movies> call, Throwable t) {

                        }
                    });
        }
    }
}
